import { request } from "@/utils/request";
import type { ScriptureList, ScriptureDetail, ApiListResponse, ResponseData, ScriptureContent } from '@/types/scripture';

const BASE_URL = import.meta.env.VITE_API_URL || '';

// 获取经书列表的参数接口
interface GetScriptureListParams {
  keyword?: string;
  pageNum: number;
  pageSize: number;
}

// 获取经书列表
export const getScriptureList = async (params: GetScriptureListParams): Promise<ApiListResponse<ScriptureList>> => {
  try {
    const { keyword = '', pageNum, pageSize } = params;
    const response = await request.get<ApiListResponse<ScriptureList>>('/scripture/basic/list', {
      data: {
        keyword,
        pageNum,
        pageSize
      }
    });
    return response as any;
  } catch (error) {
    console.error('获取经书列表失败:', error);
    return {
      code: -1,
      msg: '网络请求失败',
      rows: [],
      total: 0
    };
  }
};

// 获取经书详情章节
export const getScriptureDetails = async (scriptureId: number): Promise<ApiListResponse<ScriptureDetail>> => {
  try {
    const response = await request.get<ResponseData<ScriptureDetail[]>>(`/scripture/detail/scriptureId`, {
      data: { scriptureId }
    });
    
    if (response && Array.isArray(response.data)) {
      return {
        code: 200,
        msg: '操作成功',
        rows: response.data,
        total: response.data.length
      };
    }
    
    return {
      code: -1,
      msg: '数据格式错误',
      rows: [],
      total: 0
    };
  } catch (error) {
    console.error('获取经书详情章节失败:', error);
    return {
      code: -1,
      msg: '网络请求失败',
      rows: [],
      total: 0
    };
  }
};

// 获取章节内容
export const getScriptureContent = async (contentId: number, detailId: number): Promise<ScriptureContent | null> => {
  try {
    const response = await request.get<ResponseData<ScriptureContent>>('/scripture/content', {
      data: { contentId, detailId }
    });
    
    if (response.code === 200 && response.data) {
      return response.data as any;
    }
    
    return null;
  } catch (error) {
    console.error('获取章节内容失败:', error);
    throw error;
  }
};
